<template>
  <div class="my-container w-full h-full">
    <div class="top">
      <div class="back cursor-pointer" @click="back">
        <img
          class="w-12 h-12 lg:w-20 lg:h-20"
          src="/images/backIcon.png"
          alt=""
        />
        <span class="text-2xl lg:text-4xl text-black">返回</span>
      </div>
      <h2 class="text-2xl lg:text-4xl">面象采集</h2>
    </div>
    <div class="main">
      <video id="video" :class="isWebCamera ? '' : 'is-web'" src=""></video>
      <div class="mask">
        <div class="w-1/12 lg:w-1/3"></div>
        <div class="mask-middle w-5/6 lg:w-1/3">
          <div class="w-full"></div>
          <div class="img-area-middle h-[83.33vw] lg:h-[33.33vw]">
            <div class="photo-area2 w-[83.3vw] h-[83.3vw] lg:h-[33.34vw] lg:w-[33.34vw]" v-if="isUploadImg">
              <img class="area-mask2"  :src="imgFileData" alt="" />
            </div>
            <div class="photo-area w-[83.3vw] h-[83.3vw] lg:h-[33.34vw] lg:w-[33.34vw]">
              <img class="area-mask" src="/images/tongue-mask.png" alt="" />
            </div>
          </div>
          <div class="w-full"></div>
        </div>
        <div class="w-1/12 lg:w-1/3"></div>
      </div>
    </div>
    <button  id="left" class="w-[34vw] h-[12vw] text-[4vw] lg:w-[15vw] lg:h-[4vw] lg:text-[2vw]" v-show="btnStat[stat].showLeft" @click="rePhoto">
      {{ btnStat[stat].leftText }}
    </button>
    <button id="right" class="w-[34vw] h-[12vw] text-[4vw] lg:w-[15vw] lg:h-[4vw] lg:text-[2vw]" v-show="btnStat[stat].showRight" @click="submit">
      {{ btnStat[stat].rightText }}
    </button>
    <input
      type="file"
      id="imageUpload"
      accept="image/*"
      style="display: none"
    />
    <MyAlert ref="myAlert" />
  </div>
</template>

<script setup>
import MyAlert from "@/components/alert/index.vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
const baseUrl = import.meta.env.BASE_URL;

const router = useRouter();

const getParams = () => {
  // const url_string = window.location.href;
  // const url = new URL(url_string);
  // return url.searchParams.get("usewebcamera");
  return true;
};
const isWebCamera = getParams();

const myAlert = ref();
let imgData = "";
let stat = ref(0);
let isUploadImg = ref(false);
let imgFileData = ref()
let btnStat = {
  0: {
    showLeft: true,
    showRight: true,
    leftText: "上传图片",
    rightText: "开始采集",
  },
  1: {
    showLeft: false,
    showRight: true,
    leftText: "",
    rightText: "识别中...",
  },
  2: {
    showLeft: true,
    showRight: true,
    leftText: "重新采集",
    rightText: "确认提交",
  },
};
let myFile = "";

const back = () => {
  router.replace("/home");
};
const rePhoto = () => {
  if (stat.value === 0) {
    addImage()
    //uploadImg()
    return;
  }
  const video = document.getElementById("video");
  video.play();
  stat.value = 0;
  isUploadImg.value = false
  imgFileData.value = ''
  showMyDialog = false;
};

const submit = () => {
  if (stat.value == 0) {
    return getFaceImg();
  }
  if (stat.value == 2) {
    return submitRes();
  }
};
const submitRes = () => {
  // return uploadImg()
  // setTimeout(() => {
  //     // localStorage.setItem("face", true);
  //     // localStorage.setItem("item", "face");

  // }, 2000);
  window.localStorage.setItem('tongue_res',JSON.stringify(tongue_res))
  router.push("/home");
};
const addImage = () => {
  isUploadImg.value = true
  var input = document.getElementById("imageUpload");
  input.click(); // 模拟点击input type=file以打开文件选择对话框

  input.onchange = async () => {
    var file = input.files[0];
    if (file) {
      // 创建一个FormData对象
      imgData = file;
      let reader = new FileReader();  
      new FileReader();
      // 当文件读取完成时触发的事件  
      reader.onload = function(e) {  
          // 将读取到的文件内容（一个包含文件数据的DataURL）设置为img元素的src属性  
          imgFileData.value = e.target.result;  
      };  
      
      // 读取文件为DataURL  
      reader.readAsDataURL(file);  
      //调用舌象分析接口
      stat.value = 1;
       
      let res = await faceAnalysis();
      console.log(res);
      if (!res) {
        isUploadImg.value = false
        stat.value = 0;
        video.play();
        return;
      }
      // showDialog("采集完成");
      //如果分析失败，给出错误原因，并回滚状态
      // stat = 0
      // video.play()

      //分析成功用户决定重拍或者提交

      return (stat.value = 2);
    }
  };
};
const getFaceImg = async () => {
  const video = document.getElementById("video");

  //暂停视频，然后获取该帧视频的图片
  video.pause();
  imgData = getImgFromVideo(video);

  //调用舌象分析接口
  stat.value = 1;
  let res = await faceAnalysis();
  console.log(res);
  if (!res) {
    stat.value = 0;
    video.play();
    return;
  }
  // showDialog("采集完成");
  //如果分析失败，给出错误原因，并回滚状态
  // stat = 0
  // video.play()

  //分析成功用户决定重拍或者提交

  return (stat.value = 2);
};
const faceAnalysis = async () => {
  return new Promise((resolve, reject) => {
    uploadImg(resolve);
  });
};
const getImgFromVideo = (video) => {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  if (isWebCamera) {
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  } else {
    // 设置画布尺寸与旋转后的图像尺寸一致
    canvas.width = video.videoHeight;
    canvas.height = video.videoWidth;

    // 逆时针旋转90度
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate((-90 * Math.PI) / 180);
    ctx.drawImage(video, -video.videoWidth / 2, -video.videoHeight / 2);
  }

  //imgData是base64格式的图片
  const imgData = canvas.toDataURL("image/png");
  let arr = imgData.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  let file = new File([u8arr], "image.png", { type: mime });
  return file;
};
let tongue_res = ''
const uploadImg = (resolve) => {
  let formData = new FormData();
  formData.append("image", imgData);
  fetch("/zhensuo/admin/api/upload_tongue_data", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${window.localStorage.getItem("token")}`,
    },
    body: formData,
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.code !== 0) {
        myAlert.value.showAlert(data.message);
        return resolve(false);
      }
      tongue_res = {code:'88',...data.data}
      myAlert.value.showAlert("上传成功！");
      resolve(true);
    })
    .catch((err) => {
      myAlert.value.showAlert("上传图片失败");
      return resolve(false);
    });
};
const openVideo = () => {
  let constraints = {};
  if (isWebCamera) {
    constraints = {
      video: true,
      audio: false,
    };
  } else {
    constraints = {
      video: {
        width: {
          exact: 1600,
        },
        height: {
          exact: 1200,
        },
      },
      audio: false,
    };
  }
  navigator.mediaDevices
    .getUserMedia(constraints)
    .then((stream) => {
      // Changing the source of video to current stream.
      video.srcObject = stream;
      video.addEventListener("loadedmetadata", () => {
        video.play();
        let audio = document.getElementById("myAudio");
        audio.src = baseUrl + "/sources/tongue.mp3";
        audio.muted = false;
        audio.play();
      });
    })
    .catch((err) => {
      myAlert.value.showAlert("摄像设备打开失败");
      return;
    });
};

onMounted(() => {
  openVideo();
});
</script>

<style scoped>
.is-web {
  width: min(32vw, 100vw) !important;
  height: min(100vh, 100vw) !important;

  transform: rotate(-90deg) !important;
  transform-origin: center !important;
}
#video {
}
video {
  object-fit: contain;
  width: 100%;
  height: 100%;
}
.my-container .top {
  position: absolute;
  width: 100%;
  height: 15%;
  /* background: white; */
  /* position: relative; */
  display: flex;
  justify-content: flex-start;
  align-items: center;
  z-index: 2;
  top: 0;
  left: 0;
  /* color: white; */
}

.top .back {
  /* width: 20%; */
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.top .back img {
  width: 4rem;
  margin-right: 1rem;
  cursor: pointer;
}

.back span {
  font-size: 2rem;
  color: white;
}

.top h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2rem;
  color: white;
}

#right {
  z-index: 2;
  cursor: pointer;
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 15%;
  height: 3rem;
  font-size: 1.5rem;
  background: linear-gradient(to right, rgb(150, 150, 249), rgb(105, 105, 252));
  /* background: blue; */
  border-radius: 2rem;
  border: none;
  color: white;
}

#left {
  z-index: 2;
  cursor: pointer;
  position: fixed;
  bottom: 2rem;
  left: 2rem;
  width: 15%;
  height: 3rem;
  font-size: 1.5rem;
  background: linear-gradient(to right, rgb(150, 150, 249), rgb(105, 105, 252));
  /* background: blue; */
  border-radius: 2rem;
  border: none;
  color: white;
}

button {
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  border-radius: 100vw !important;
}

.main {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: 0;

  display: flex;
  justify-content: center;
  align-items: center;
}

/* video {
    width: 100%;
    height: 100%;
    object-fit: cover;
} */

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  /* background-color: rgba(0, 0, 0, 0.2); */

  display: flex;
  /* justify-content: center;
        align-items: center; */
}

.mask > div {
  background-color: #fff;
  color: #000;
  
  height: 100vh;
}

.mask .mask-middle {
  flex-shrink: 0;
  background-color: transparent;
  height: 100vh;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.mask-middle > div {
  
  height: 50vh;

  background-color: #fff;
}

.img-area-middle {
  position: relative;
  
  flex-shrink: 0;
  background-color: transparent !important;
}

.photo-area {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  
  background: radial-gradient(
    transparent 0%,
    transparent 65%,
    #17fad1 65.5%,
    #17fad1 70%,
    #fff 70.5%,
    #fff 100%
  ) !important;

  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}
.photo-area2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  

  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  border-radius: 100%;
  overflow: hidden;
}
.area-mask {
  width: 68%;
}
.area-mask2 {
  width: 100%;
}
</style>
